package cn.mumzone.pos.util;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.BuildConfig;
import cn.mumzone.pos.api.ApiRequest;
import cn.mumzone.pos.event.DownloadChangeEvent;
import okhttp3.ResponseBody;
import retrofit2.Response;
import rx.functions.Action1;

import static android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

/**
 * Created by qiuzhenhuan on 2019/2/12.
 */
public class UpdateAppService extends IntentService {

    private static final String TAG = "UpdateAppService";


    public UpdateAppService() {
        super(TAG);
    }


    protected void onHandleIntent(Intent intent) {
        try {

            // 开始下载
            downloadFile(AppConstants.URL_APK_DOWMLOAD_PATH);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件下载
     *
     * @param downloadUrl
     */
    private void downloadFile(String downloadUrl) {

        ApiRequest.getAppService().getApkFile(downloadUrl).subscribe(new Action1<Response<ResponseBody>>() {
            @Override
            public void call(Response<ResponseBody> response) {

                BufferedOutputStream outputStream = null;
                BufferedInputStream inputStream = null;
                try {
                    File apkFile = FileUtil.getApkFile(getApplicationContext());//输出文件名
                    if (apkFile.exists()) {
                        apkFile.delete();
                    }
                    Elog.e(TAG, "下载启动：" + AppConstants.URL_APK_DOWMLOAD_PATH + " --to-- " + apkFile.getPath());

                    outputStream = new BufferedOutputStream(new FileOutputStream(apkFile));
                    inputStream = new BufferedInputStream(response.body().byteStream());
                    byte[] fileReader = new byte[4096];
                    long fileSize = response.body().contentLength();
                    long fileSizeDownloaded = 0;
                    Elog.e(TAG, "下载长度 ：" + Math.ceil(fileSize / 1024));
                    Elog.e(TAG, "下载中...");
                    int progress = 0;
                    while (true) {
                        int read = inputStream.read(fileReader);
                        if (read == -1) {
                            break;
                        }
                        outputStream.write(fileReader, 0, read);
                        fileSizeDownloaded += read;
//                        int nowProgress = (int) ((Double.longBitsToDouble(fileSizeDownloaded) / Double.longBitsToDouble(fileSize)) * 100);
                        int nowProgress = (int) (BigDecimalUtil.div(Long.toString(fileSizeDownloaded), Long.toString(fileSize)) * 100);
                        if (nowProgress > progress) {
                            progress = nowProgress;
                            Elog.e(TAG, String.format("下载进度 ：%s%%", progress));
                            RxBus.getDefault().post(new DownloadChangeEvent(progress));
                        }
                    }
                    outputStream.flush();

                    // 下载结束
                    Elog.e(TAG, String.format("下载结束  下载长度:%s", apkFile.length()));
                    Elog.e(TAG, String.format("下载结束  文件地址:%s", apkFile.getAbsolutePath()));
                    Intent install = new Intent(Intent.ACTION_VIEW);
                    Uri data;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        data = FileProvider.getUriForFile(UpdateAppService.this, BuildConfig.APPLICATION_ID+".fileProvider", apkFile);
                    } else {
                        data = Uri.fromFile(apkFile);
                    }
                    Elog.e(TAG, String.format("下载结束  Uri:%s", data.toString()));
                    install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION| FLAG_GRANT_WRITE_URI_PERMISSION);//允许临时的读和写
                    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    install.setDataAndType(data, "application/vnd.android.package-archive");
                    startActivity(install);

                } catch (IOException e) {
                    e.printStackTrace();
                    Elog.e(TAG, "下载异常");
                    RxBus.getDefault().post(new DownloadChangeEvent(-1));
                    PosToast.INSTANCE.makeShortToast(getApplicationContext(), "下载异常");

                } finally {
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }

            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable e) {
                e.printStackTrace();
                Elog.e(TAG, "下载异常");
                RxBus.getDefault().post(new DownloadChangeEvent(-1));
                PosToast.INSTANCE.makeShortToast(getApplicationContext(), "下载异常");
            }
        });

    }


    public static void startDownloadService(Context context) {
        Intent intent = new Intent(context, UpdateAppService.class);
        context.startService(intent);
    }
}
